package com.supermarket.config; // 正确的包路径

// 依赖导入
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Redis配置类
 * 配置RedisTemplate和缓存管理器
 */
@Configuration
@EnableCaching // 启用缓存注解
public class RedisConfig extends CachingConfigurerSupport {

    /**
     * 创建支持Java 8日期时间的ObjectMapper
     * @return 配置好的ObjectMapper
     */
    private ObjectMapper createObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 注册Java 8日期时间模块
        objectMapper.registerModule(new JavaTimeModule());
        // 禁用将日期时间序列化为时间戳的默认行为
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        // 设置所有字段可见
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 启用默认类型，确保反序列化时能正确转换对象类型
        objectMapper.activateDefaultTyping(
            LaissezFaireSubTypeValidator.instance, 
            ObjectMapper.DefaultTyping.NON_FINAL
        );
        return objectMapper;
    }

    /**
     * 配置RedisTemplate
     * 设置Key和Value的序列化方式
     * @param factory Redis连接工厂
     * @return RedisTemplate对象
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(factory);
        
        // 创建JSON序列化器
        ObjectMapper objectMapper = createObjectMapper();
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
        
        // 设置String类型key的序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);
        
        // 设置值和Hash值的序列化器
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        template.afterPropertiesSet();
        return template;
    }
    
    /**
     * 配置Redis缓存管理器
     * 用于@Cacheable等注解使用
     * @param factory Redis连接工厂
     * @return 缓存管理器
     */
    @Bean
    public RedisCacheManager cacheManager(RedisConnectionFactory factory) {
        // 创建String序列化器
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        
        // 创建JSON序列化器
        ObjectMapper objectMapper = createObjectMapper();
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
        
        // 默认缓存配置
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
            // 设置缓存前缀
            .prefixCacheNameWith("campus:")
            // 设置缓存过期时间为1小时
            .entryTtl(Duration.ofHours(1))
            // 设置Key的序列化器
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringRedisSerializer))
            // 设置Value的序列化器
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
            // 不缓存null值
            .disableCachingNullValues();
            
        // 为不同的缓存名称配置不同的过期时间
        Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
        // 商品缓存，过期时间2小时
        configMap.put("product", defaultConfig.entryTtl(Duration.ofHours(2)));
        // 用户缓存，过期时间4小时
        configMap.put("user", defaultConfig.entryTtl(Duration.ofHours(4)));
        // 文章缓存，过期时间6小时
        configMap.put("article", defaultConfig.entryTtl(Duration.ofHours(6)));
        // 订单缓存，过期时间30分钟
        configMap.put("order", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        return RedisCacheManager.builder(factory)
            .cacheDefaults(defaultConfig)
            .withInitialCacheConfigurations(configMap)
            .transactionAware()
            .build();
    }
}
